import random

import soundfile as sf
import matplotlib.pyplot as plt
import time
import os
import musicpy as mp

from dataset import get_files, load_audio_as_spec
from simpledaw import SimpleDAW

preset_dir = r"B:\muse_repo\Presets\_Legacy"
midi_dir = r"F:\编曲资源"
output_dir = r"C:\dev_spa\DMuse\202202b5"

midi_output_dir = output_dir + r"\random_midi"

if not os.path.exists(output_dir):
    os.mkdir(output_dir)
    # os.mkdir(midi_output_dir)

fxp_files = get_files(preset_dir, 'fxp')
mid_files = get_files(midi_dir, 'mid')

'''for i in range(1000):
    chord1 = mp.random_composing(mp.scale('C5', 'major'), 32)
    mp.play(chord1)
    mp.write(chord1, midi_output_dir + '\\' + str(i) + '.mid')'''

simple_daw = SimpleDAW(plugin='C:/VST/64bit/Sylenth1.dll', sample_rate=44100, bpm=120)

counter = 0
with open(output_dir + '\\' + 'params.txt', 'wt') as file:
    for i, fxp in enumerate(fxp_files[:100]):
        simple_daw.load_preset(fxp)
        for j in range(100):
            simple_daw.load_midi(random.choice(mid_files))
            audio = simple_daw.render(2.)
            output_filename = output_dir + '\\' + str(counter) + '.wav'
            counter += 1
            sf.write(output_filename, audio, samplerate=44100)

            file.write(','.join(str(param) for param in simple_daw.get_params()) + '\n')

        # spec = load_audio_as_spec(output_filename, (224, 224), 100.)
        # plt.imshow(spec[..., 0])
        # plt.show()
        # time.sleep(1)

